import json

from django.shortcuts import render,redirect
from django.urls import reverse
from system.models import User,Goods,Unit,GoodsType,TransactionRecords,Log

import socket    #获取ip地址用

#接口
from django.http import HttpResponse,JsonResponse
from django.views.decorators.csrf import csrf_exempt

from system.views import SUCCESS_CODE,ERR_CODE,ERR_TIMEOUT,SUCCESS_MESSAGE,ERR_MESSAGE

# 删除用户
@csrf_exempt
def deleteUser(request):
    dic = {}
    if request.method == 'GET':
        userId = request.GET.get('userId')

        if userId:
            info = User.objects.filter(id=userId)
            if info:
                info[0].delete()
                dic['code'] = SUCCESS_CODE
                dic['message'] = SUCCESS_MESSAGE
            else:
                dic['code'] = ERR_CODE
                dic['message'] = '账号不存在'
        else:
            dic['code'] = ERR_CODE
            dic['message'] = '请选择正确的用户名'
    else:
        dic['code'] = ERR_CODE
        dic['message'] = ERR_MESSAGE
    return JsonResponse(dic, json_dumps_params={'ensure_ascii': False})


# 修改用户数据
@csrf_exempt
def editUser(request):
    dic = {}
    if request.method == 'POST':
        user_id = request.GET.get('id')
        operator_id = request.GET.get('username')   # 操作员
        operator = User.objects.filter(id=operator_id)[0]

        # 只有自己或者管理员可以修改信息
        if (operator.id == id or operator.level == 2) and request.body:
            data = request.body.decode('utf-8')   # 把发送的数据转换成utf-8
            json_data = json.loads(data)     # 把json数据转换成字典
            username = json_data.get('username')    # 提取字典中的数据
            password = json_data.get('password')
            level = json_data.get('level')

            user = User.objects.filter(id=user_id)[0]
            user.username = username
            user.password = password
            user.level = level
            user.save()

            dic['code'] = SUCCESS_CODE
            dic['message'] = '修改成功'
        else:
            dic['code'] = ERR_CODE
            dic['message'] = '没有权限'
    else:
        dic['code'] = ERR_CODE
        dic['message'] = ERR_MESSAGE

    return JsonResponse(dic, json_dumps_params={'ensure_ascii': False})





